<template>
  <a-modal
    :title="$t('人工发券')"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @cancel="handleCancel"
    class="customHeight customHeightChild modal_title"
    v-drag
  >
    <template slot="footer">
      <a-button @click="handleCancel" :loading="confirmLoading">{{ $t('取消') }}</a-button>
      <a-button type="primary" @click="handleOk" :loading="confirmLoading">{{ $t('发券') }}</a-button>
    </template>
    <a-row>
      <a-col :span="24" style="margin-bottom: 20px">
        <div>
          <span>{{ $t('会员') }}：</span>
          <a-auto-complete
            v-model="keyWord"
            @select="onSelect"
            :filter-option="false"
            :dropdown-match-select-width="false"
            :dropdownMenuStyle="{ width: '500px' }"
            style="width: 400px"
            option-label-prop="key"
          >
            <template slot="dataSource">
              <a-select-opt-group v-for="(group,i) in memberData" :key="group.title+i">
                <span slot="label"
                  ><span style="display: inline-block; width: 110px">{{ $t('手机号') }}</span>
                  <span style="display: inline-block; width: 110px">{{ $t('卡号') }}</span>
                  <span style="display: inline-block; width: 150px">{{ $t('姓名') }}</span>
                  <span style="display: inline-block; width: 90px">{{ $t('币值') }}</span>
                </span>
                <a-select-option v-for="item in group.memberList" :key="item.memberId" :value="item">
                  <span style="display: inline-block; width: 110px">{{ item.phone }}</span>
                  <span style="display: inline-block; width: 110px">{{ item.memberCardNo }}</span>
                  <span style="display: inline-block; width: 150px">{{ item.name }}</span>
                  <span style="display: inline-block; width: 90px">{{ item.totalCoin }}</span>
                </a-select-option>
              </a-select-opt-group>
            </template>
            <a-input-search
              :placeholder="$t('请输入会员手机号/卡号/姓名')"
              @search="searchMember"
              enter-button
            ></a-input-search>
          </a-auto-complete>
        </div>
      </a-col>
      <a-col :span="24" style="margin-bottom: 20px">
        <div style="margin-bottom: 10px; font-weight: 600; color: rgba(0, 0, 0, 0.8)">{{ $t('会员') }}</div>
        <a-table
          row-key="memberId"
          :columns="columns"
          :dataSource="dataSource"
          :scroll="{ y: 240 }"
          :pagination="false"
          bordered
          style="border: 1px solid #e5e5e5"
          class="customTable"
        ></a-table>
      </a-col>
      <a-col :span="24">
        <div style="margin-bottom: 10px; font-weight: 600; color: rgba(0, 0, 0, 0.8)">{{ $t('优惠券') }}</div>
        <a-table
          row-key="couponId"
          :columns="columns1"
          :dataSource="dataSource1"
          :scroll="{ y: 200 }"
          :pagination="false"
          bordered
          style="border: 1px solid #e5e5e5"
          class="customTable"
        >
          <template slot="action" slot-scope="text, record, index">
            <a-icon type="close" @click="deleteCoupon(index)" />
          </template>
          <template slot="selectThree" slot-scope="text, record">
            <div>
              <a-select
                v-model="record.couponId"
                show-search
                :placeholder="$t('请选择优惠券')"
                :filter-option="false"
                style="width: 100%"
                :not-found-content="null"
                @search="handleSearchCoupon"
              >
                <a-select-option
                  v-for="(good, i) in couponList"
                  :key="i"
                  :value="good.couponId"
                  @click="handleCoupon(record, good)"
                  >{{ good.couponId_dictText }}</a-select-option
                >
              </a-select>
            </div>
          </template>
          <template slot="inputAmount" slot-scope="text, record">
            <div>
              <a-input v-model="record.number"></a-input>
            </div>
          </template>
        </a-table>
      </a-col>
    </a-row>
  </a-modal>
</template>
<script>
import { getAction, postAction } from '@/api/manage'
let that
export default {
  name: 'SendCouponModal',
  data() {
    return {
      width: 600,
      visible: false,
      confirmLoading: false,
      keyWord: undefined,
      memberData:[],
      couponList: [],
      columns: [
        {
          title: this.$t('手机号'),
          align: 'center',
          dataIndex: 'phone',
          width: 150,
        },
        {
          title: this.$t('卡号'),
          align: 'center',
          dataIndex: 'memberCardNo',
          width: 130,
        },
        {
          title: this.$t('姓名'),
          align: 'center',
          dataIndex: 'name',
          width: 150,
        },
        {
          title: this.$t('币值'),
          align: 'right',
          dataIndex: 'totalCoin',
        },
      ],
      columns1: [
        {
          title: this.$t('优惠券名称'),
          align: 'center',
          dataIndex: 'couponId_dictText',
          width: 320,
          scopedSlots: { customRender: 'selectThree' },
        },
        {
          title: this.$t('数量'),
          align: 'center',
          dataIndex: 'number',
          width: 100,
          scopedSlots: { customRender: 'inputAmount' },
        },
        {
          title: '+',
          dataIndex: 'action',
          align: 'center',
          customHeaderCell: function (column) {
            return {
              style: {
                textAlign: 'center',
                color: '#1890ff',
                fontSize: '25px',
                height: '32px',
                lineHeight: '32px',
                fontWeight: 'bold',
                cursor: 'pointer',
              },
              on: {
                click: () => {
                  that.addCoupon()
                },
              },
            }
          },
          customCell: function (column) {
            return {
              style: {
                textAlign: 'center',
                color: '#1890ff',
                fontSize: '16px',
                height: '32px',
                lineHeight: '32px',
                fontWeight: 'bold',
                cursor: 'pointer',
              },
            }
          },
          scopedSlots: { customRender: 'action' },
        },
      ],
      dataSource: [],
      dataSource1: [],
    }
  },
  created() {
    that = this
  },
  methods: {
    add() {
      that.dataSource = []
      that.edit()
    },
    edit(list) {
      if (list) {
        that.dataSource = list
      }
      that.confirmLoading = false
      that.memberData = []
      that.couponList = []
      that.dataSource1 = []
      that.keyWord = undefined
      that.visible = true
    },
    handleCancel() {
      that.visible = false
    },
    searchMember() {
      let query = {}
      query.memberInfo = that.keyWord
      query.pageNo = 1
      query.pageSize = 20
      query.state = '0'
      that.memberData = [];
      getAction('/member/bisMemberInfo/list', query).then((res) => {
        if (res.success) {
          let memberList=[]
          res.result.records.forEach((rds) => {
            rds.memberCardNo = ''
            rds.totalCoin = (rds.memberAccount.realCoin + rds.memberAccount.presentCoin).toFixed(2)
            if (rds.memberCards && rds.memberCards.length > 0) {
              rds.memberCardNo = rds.memberCards.filter((m) => {
                return m.state == 0
              })[0].chipNo
            }
            let obj = {
              memberId: rds.id,
              memberCardNo: rds.memberCardNo,
              phone: rds.phone,
              totalCoin: rds.totalCoin,
              name: rds.name,
            }
            memberList.push(obj)
          })
          that.memberData.push({ memberList: memberList })
        }
      })
    },
    onSelect(value) {
      let member = JSON.parse(JSON.stringify(value));
      let x = that.dataSource.findIndex((m) => {
        return member.memberId == m.memberId
      })
      if (x == -1) {
        that.dataSource.push(member)
      }
      that.keyWord = undefined
    },
    handleOk() {
      let param = {}
      if (!that.dataSource.length) {
        that.$message.error(that.$t('请输入会员手机号/卡号/姓名'))
        return
      }
      param.memberList = that.dataSource
      let arr = that.dataSource1.filter((ds) => {
        return ds.couponId && ds.number != 0
      })
      if (!arr.length) {
        that.$message.error(that.$t('请设置优惠券'))
        return
      }
      param.couponList = arr
      that.confirmLoading = true
      postAction('/member/bisManualCouponRecord/manualCouponList', param)
        .then((res) => {
          if (res.success) {
            that.$message.success(res.message)
            that.handleCancel()
            that.$emit('ok')
          } else {
            that.$message.warning(res.message)
          }
        })
        .finally(() => {
          that.confirmLoading = false
        })
    },
    addCoupon() {
      let obj = {
        couponId: undefined,
        couponId_dictText: '',
        number: '',
      }
      that.dataSource1.push(obj)
    },
    deleteCoupon(i) {
      this.dataSource1.splice(i, 1)
    },
    handleSearchCoupon(value) {
      let query = {}
      query.form = 9
      query.pageNo = 1
      query.pageSize = 20
      query.goodsInfo = value
      query.state = 'Y'
      that.couponList=[]
      getAction('/goods/bisGoodsInfor/list', query).then((res) => {
        if (res.success) {
          res.result.records.forEach((rds) => {
            let obj = {
              couponId: rds.id,
              couponId_dictText: rds.name,
            }
            that.couponList.push(obj)
          })
        }
      })
    },
    handleCoupon(record, good) {
      record.couponId_dictText = good.couponId_dictText
    },
  },
}
</script>